#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>

void Usage(std::string proc)
{
    std::cout << proc << "IP port" << std::endl;
}
int main(int args, char *argv[])
{
    if (args != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket is error" << errno << std::endl;
        return 2;
    }
    // 客户端不需要手动bind

    // 连接客户端
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);
    socklen_t len = sizeof(server);
    if (connect(sock, (sockaddr *)&server, len) < 0)
    {
        std::cerr << "connect is error" << errno << std::endl;
        return 3;
    }
    // 使用服务
    while (true)
    {
        std::string buffer;
        std::cin >> buffer;
        write(sock, buffer.c_str(), buffer.size());

        char arr[2048];
        memset(arr, 0, sizeof(arr));
        ssize_t size = read(sock, (void *)arr, sizeof(arr));
        arr[size] = 0;
        std::cout << "server #" << arr << std::endl;
    }

    return 0;
}